package binarysearch

import (
	"fmt"
)

const testVersion = 1

func search(slice []int, find int) (position int) {
	if slice == nil {
		position = -1
		return
	}

	count := len(slice)
	for i := 0; i < count; i++ {
		if find > slice[i] {
			position = i
		}
	}
	return
}

func SearchInts(slice []int, find int) (position int) {
	position = search(slice, find)
	if -1 == position {
		position = 0
		return
	}

	if find > slice[position] {
		position = position + 1
	}

	return
}

func Message(slice []int, find int) string {
	position := search(slice, find)

	if position == -1 {
		return "slice has no values"
	}

	if position == 0 {
		if find == slice[position] {
			return fmt.Sprintf("%v found at beginning of slice", find)
		} else {
			if find == slice[position+1] {
				return fmt.Sprintf("%v found at index %v", find, position+1)
			}

			if find < slice[position] {
				return fmt.Sprintf("%v < all values", find)
			}
		}
	}

	if position == len(slice)-1 {
		if find == slice[position] {
			return fmt.Sprintf("%v found at end of slice", find)
		} else {
			if find > slice[position] {
				return fmt.Sprintf("%v > all %v values", find, len(slice))
			}
		}
	}

	if find == slice[position+1] {
		if position+1 == len(slice)-1 {
			return fmt.Sprintf("%v found at end of slice", find)
		} else {
			return fmt.Sprintf("%v found at index %v", find, position+1)
		}
	}

	if find > slice[position] && find < slice[position+1] {
		return fmt.Sprintf("%v > %v at index %v, < %v at index %v",
			find, slice[position], position,
			slice[position+1], position+1)
	}

	return "errors"
}
